package cirno.open.api.service.impl;

import cirno.open.api.common.ErrorCode;
import cirno.open.api.config.ContainerPoolExecutor;
import cirno.open.api.dao.DockerDao;
import cirno.open.api.entity.ExecuteRequest;
import cirno.open.api.entity.ExecuteResponse;
import cirno.open.api.enums.LanguageCmdEnum;
import cirno.open.api.exception.BusinessException;
import cirno.open.api.service.DockerSandboxService;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class DockerSandboxServiceImpl implements DockerSandboxService {
    @Resource
    private DockerDao dockerDao;

    @Resource
    private ContainerPoolExecutor containerPoolExecutor;

    @Override
    public void validateParams(ExecuteRequest request) {
        String code = request.getCode();
        String language = request.getLanguage();
        if (StringUtils.isAnyBlank(code, language)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!LanguageCmdEnum.getLanguages().contains(language)) {
            log.error("code = {} ", language);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不支持的语言类型");
        }
        if (code.trim().length() > 10000) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "代码过多");
        }
    }

    @Override
    public ExecuteResponse execute(LanguageCmdEnum languageCmdEnum, String code , boolean onlyCompile) {
        return containerPoolExecutor.run(containerInfo -> {
            try {
                String containerId = containerInfo.getContainerId();
                String codePathName = containerInfo.getCodePathName();
                String codeFileName = codePathName + File.separator + languageCmdEnum.getSaveFileName();
                FileUtil.writeString(code, codeFileName, StandardCharsets.UTF_8);
                dockerDao.copyFileToContainer(containerId, codeFileName);
                // 编译代码
                String[] compileCmd = languageCmdEnum.getCompileCmd();
                log.info("compileCmd =  {}", Arrays.toString(compileCmd));
                ExecuteResponse executeResponse = null;
                // 不为空则代表需要编译
                if (compileCmd != null) {
                    executeResponse = dockerDao.execCmd(containerId, compileCmd);
                    log.info("compile complete | result = {}", executeResponse);
                    // 语法通过不会有任何提示信息，如果存在，则表示不合法
                    if (!executeResponse.getMessage().isEmpty()) {
                        executeResponse.setErrorMessage(executeResponse.getMessage());
                        executeResponse.setMessage(null);
                        executeResponse.setSuccess(false);
                        return executeResponse;
                    }
                }

                //仅编译
                if (onlyCompile) {
                    //清除代码
                    if (!FileUtil.del(codeFileName)) {
                        log.error("清除临时代码文件失败：{}", codeFileName);
                    }
                    return executeResponse;
                }

                //拆分命令
                List<String[]> runCmds = splitArrayByDelimiter(languageCmdEnum.getRunCmd(), "&&");
                //运行代码
                for (String[] runCmd : runCmds) {
                    executeResponse = dockerDao.execCmd(containerId, runCmd);
                    log.info("runCmd = {}", Arrays.toString(runCmd));
                    log.info("run complete | result = {}", executeResponse);
                }
                //清除代码
                if (!FileUtil.del(codeFileName)) {
                    log.error("清除临时代码文件失败：{}", codeFileName);
                }
                return executeResponse;
            } catch (Exception e) {
                return ExecuteResponse.builder()
                        .success(false)
                        .errorMessage(e.getMessage())
                        .build();
            }
        });
    }

    @Override
    public ExecuteResponse compile(LanguageCmdEnum languageCmdEnum, String code) {
       return execute(languageCmdEnum,code,true);
    }


    private List<String[]> splitArrayByDelimiter(String[] array, String delimiter) {
        List<String[]> splitResult = new ArrayList<>();
        List<String> currentList = new ArrayList<>();

        for (String element : array) {
            if (element.equals(delimiter)) {
                if (!currentList.isEmpty()) {
                    splitResult.add(currentList.toArray(new String[0])); // 转换成 String[] 并添加
                    currentList.clear(); // 清空 currentList，准备下一个子数组
                }
            } else {
                currentList.add(element);
            }
        }
        // 添加最后一组元素
        if (!currentList.isEmpty()) {
            splitResult.add(currentList.toArray(new String[0]));
        }
        return splitResult;
    }
}
